import { reqGoodsList } from '../../../api/goods'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [], // 商品列表数据
    total: 0,
    isFinish: false, // 判断数据是否加载完毕 数据
    isLoading: false, // 判断数据是否加载完毕 节流
    // 商品列表请求参数
    requestData: {
      page: 1,
      limit: 10,
      category1Id: '',
      category2Id: ''
    }
  },
  // 获取商品
  async getGoodsList () {
    this.data.isLoading = true
    const { data } = await reqGoodsList(this.data.requestData)
    this.data.isLoading = false
    this.setData({
      goodsList: [...this.data.goodsList, ...data.records],
      total: data.total
    })
  },
  onLoad(options) {
    // 合并category1Id category2Id
    Object.assign(this.data.requestData, options)
    this.getGoodsList()
  },
  // 触底加载
  onReachBottom () {
    const { goodsList, total, requestData:{page}, isLoading } = this.data
    // 如果isloading为true,说明请求发送中,就不执行后续
    if(isLoading) return
    if(goodsList.length >= total) {
      this.setData({
        isFinish: true
      })
      return
    }
    this.setData({
      requestData: { ...this.data.requestData, page: page+1 }
    })
    this.getGoodsList()
  },
  // 上啦刷新
  onPullDownRefresh () {
    // 重置数据
    this.setData({
      goodsList: [], // 商品列表数据
      total: 0,
      isFinish: false, // 判断数据是否加载完毕
      isLoading: false, // 判断数据是否加载完毕
      // 商品列表请求参数
      requestData: {...this.data.requestData, page: 1}
    })
    this.getGoodsList()
    // 手动关闭下拉刷新效果
    wx.stopPullDownRefresh()
  },
})